package club.jdiy.dev.view;

import club.jdiy.admin.freemarker.func.*;
import club.jdiy.utils.Md5Utils;
import club.jdiy.utils.StringUtils;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

public class FtlParser {
    private final Configuration configuration;
    private final Map<String, Object> model;

    @Resource
    private TimestampToDate timestampToDate;
    @Resource
    private GetUserInfo getUserInfo;

    public FtlParser(Configuration configuration, Map<String, Object> model) {
        this.configuration = configuration;
        this.model = model == null ? new HashMap<>() : model;
        //configuration.setSharedVariable("to_date", timestampToDate);
        //configuration.setSharedVariable("getUserInfo", getUserInfo);
    }

    /**
     * 添加模型数据变量值.
     *
     * @param var 变量名称
     * @param o   变量值
     * @return ElParser
     */
    public FtlParser addVariable(String var, Object o) {
        this.model.put(var, o);
        return this;
    }

    /**
     * 移除模型数据变量值.
     *
     * @param var 变量名称
     * @return ElParser
     */
    public FtlParser removeVariable(String var) {
        this.model.remove(var);
        return this;
    }

    public String parse(String templateStr) throws IOException, TemplateException {
        if (StringUtils.isEmpty(templateStr) || !templateStr.contains("${") && !templateStr.contains("<#"))
            return templateStr;
        String key = Md5Utils.md5(templateStr);
        StringTemplateLoader stl = new StringTemplateLoader();
        stl.putTemplate(key, templateStr);
        configuration.setTemplateLoader(stl);
        Template template = configuration.getTemplate(key);
        StringWriter writer = new StringWriter();
        template.process(model, writer);
        return writer.toString();
    }

    public boolean condition(String condition) throws IOException, TemplateException {
        return "true".equals(this.parse("${(" + condition + ")?string('true','false')}"));
    }

}
